import axios, { InternalAxiosRequestConfig, AxiosResponse } from "axios";
import { useUserStoreHook } from "@/store/modules/user";

/**
 * 后期可以采用这种形式，域名通过nginx指向接口地址进行代理; 便于前端只打一个包，就可以部署多地方
 * const urlHostName = `http://${window.location.hostname}:9099`;
 * baseURL: import.meta.env.VITE_ENV === 'development' ? import.meta.env.VITE_GLOB_API_URL_PREFIX : urlHostName,
 */

// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_GLOB_API_URL_PREFIX,
  timeout: 50000,
  headers: { "Content-Type": "application/json;charset=utf-8" },
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const userStore = useUserStoreHook();
    if (userStore.token) {
      config.headers.Authorization = userStore.token;
    }
    // 默认入参添加机构id与用户ID
    const oid = Number(localStorage.getItem("oid"));
    const operatorId = Number(localStorage.getItem("userId"));
    const userId = Number(localStorage.getItem("userId"));
    const timestamp = Date.now(); // 获取当前时间戳
    if (config.method === "get" || config.method === "delete") {
      if (config.params?.hide || config.data?.hide) {
        config.params = {
          ...config.params,
          operatorId,
          userId,
          timestamp,
        };
      } else {
        config.params = {
          ...config.params,
          oid,
          operatorId,
          userId,
          timestamp,
        };
      }
    } else if (config.method === "post" || config.method === "put") {
      config.data = {
        ...config.data,
        oid,
        operatorId,
        userId,
        timestamp,
      };
    }
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    let errorMgs: any;
    if (response?.config?.method === "get" || response?.config?.method === "delete") {
      const { mgsError } = response.config.params;
      errorMgs = mgsError;
    } else if (response?.config?.method === "post" || response?.config?.method === "put") {
      const { mgsError } = response.config.data;
      errorMgs = mgsError;
    }
    // TODO
    // 暂时用success判断, 等后台规划好statusCode, 在使用statusCode
    const { statusCode, msg, success, data } = response.data;
    if (success) {
      return data;
    }
    // 响应数据为二进制流处理(Excel导出)
    if (response.data instanceof ArrayBuffer) {
      return response;
    }
    // 信息不提示
    if (errorMgs) return Promise.reject();
    ElMessage.error(data?.msg || msg || "系统出错");
    return Promise.reject(new Error(msg || "Error"));
  },
  (error: any) => {
    if (error?.response?.data) {
      const { code, msg } = error.response.data;
      // token 过期,重新登录
      if (code === "A0230") {
        ElMessageBox.confirm("当前页面已失效，请重新登录", "提示", {
          confirmButtonText: "确定",
          type: "warning",
        }).then(() => {
          const userStore = useUserStoreHook();
          userStore.resetToken().then(() => {
            location.reload();
          });
        });
      } else {
        ElMessage.error(msg || "系统出错");
      }
    }else{
      ElMessage.error(error.message || "系统出错");
    }
    return Promise.reject(error.message);
  }
);

// 导出 axios 实例
export default service;
